package logic.netSerer.GUI.nettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import logic.util.EasyLog;

public class NettyServer {
	public static int port;	//端口
	public static NioEventLoopGroup bossGroup=new NioEventLoopGroup();//	连接组
	public static NioEventLoopGroup workGroup=new NioEventLoopGroup();//	工作组
	public void initData(){
		port=8301;
		}
	public void start(){
		ServerBootstrap bootstrap=new ServerBootstrap();	//创建启动项
		bootstrap.group(bossGroup, workGroup);	//绑定连接组与工作组(连接组为父组)
		bootstrap.channel(NioServerSocketChannel.class);//设定频道实现
		bootstrap.option(ChannelOption.SO_BACKLOG, 128);	//?
		bootstrap.option(ChannelOption.TCP_NODELAY, true);	//无延迟发出
		bootstrap.option(ChannelOption.SO_REUSEADDR, true);	//?
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);	//保持长连接
		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {	//初始化接收处理行为
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline=ch.pipeline();	//为频道添加处理管线
				pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));//为管线添加字符编码解码器
				pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));//为管线添加字符编码加密器
				//添加消息处理器
				pipeline.addLast(new NettyServerHandle());	
			}
		});
//
		//启动端口
		ChannelFuture future;
		try{
			future=bootstrap.bind(port).sync();
			if(future.isSuccess()){
				EasyLog.info(getClass(),"端口 {} 已成功绑定.",port);
			}
		}catch (InterruptedException e) {
		EasyLog.info(getClass(), "端口 {} 已成功绑定.", port);	
		}
	}
	public static void shut(){
		workGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
		EasyLog.info(NettyServer.class,"端口{} 已成功解绑.",port);
	}
	
	public static void main(String...args){
		NettyServer nettyServer=new NettyServer();
		NettyServer.port=8301;
		nettyServer.start();
		EasyLog.info(NettyServer.class, "Netty 服务端已启动");
	}
	
}
